package com.zby.test.query;

import com.zby.test.util.factory.Session;
import com.zby.test.util.factory.SessionClose;
import com.zby.test.util.factory.SqlSessionFactory;
import com.zby.test.util.reflect.PersistentObject;
import com.zby.test.vo.Project;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

/**
 * Created By zby on 16:48 2019/1/23
 * 采用类字面常量获取当前对象
 */

public class SqlQuery<T extends Object> {

    /**
     * sql语句
     */
    private String sql;

    /**
     * 与数据库的连接
     */
    private Connection connection;

    /**
     * 类字面常量
     */
    private Class<T> persistenceClass;


    public SqlQuery() {
    }

    public SqlQuery(Connection connection, String sql) {
        this.sql = sql;
        this.connection = connection;
    }

    public SqlQuery(Class<T> persistenceClass, Connection connection, String sql) {
        this(connection, sql);
        this.persistenceClass = persistenceClass;
    }

    /**
     * Created By zby on 19:18 2019/1/27
     * 创建类型
     */
    public SqlQuery addScalar(String alias, String type) {
        return this;
    }

    /**
     * Created By zby on 23:19 2019/1/23
     * 体检反射的实体类
     */
    private SqlQuery addEntity(Class<T> persistenceClass) {
        this.persistenceClass = persistenceClass;
        return this;
    }


    /**
     * Created By zby on 16:41 2019/1/24
     * 查找值
     */
    public List<T> list() {
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            PersistentObject persistentObject = new PersistentObject(persistenceClass, resultSet);
            return persistentObject.getPersist();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SessionClose.closeConnStateResSet(connection, statement, resultSet);
        }
        return null;
    }


    public static void main(String[] args) {
        Session session = new SqlSessionFactory().openSession();
        String sql = "SELECT p.* from project p;";
        List<Project> projects = session.createSqlQuery(sql).addEntity(Project.class).list();
        for (Project project : projects) {
            System.out.println(project.getCustomerName() + "\t" + project.isDeleted());
        }
    }
}
